# 这是一个简单的Scheme
from marshmallow import Schema, fields
import datetime as dt


class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.created_time = dt.datetime.now()


class UserSchema(Schema):
    name = fields.String()
    email = fields.Email()
    created_time = fields.DateTime()


user = User("lhh", "2432783449@qq.com")
schema = UserSchema()
res = schema.dump(user)
print(res)
# {'email': '2432783449@qq.com', 'created_time': '2021-05-28 20:43:08.946112', 'name': 'lhh'}  dict

res2 = schema.dumps(user)
print(res2)
# {"name": "lhh", "email": "2432783449@qq.com", "created_time": "2021-05-28 20:45:17.418739"}  json


summary_schema = UserSchema(only={"name", "email"})
res = summary_schema.dump(user)
print(res)


user_data = {
    "name": "lhh",
    "email": "2432783449@qq.com",
    "created_time": "2021-05-28 20:45:17.418739"
}
schema = UserSchema()
res = schema.load(user_data)
print(res)
# {'created_time': '2021-05-28 20:45:17.418739', 'email': '2432783449@qq.com', 'name': 'lhh'}


user1 = User(name="lhh1", email="2432783449@qq.com")
user2 = User(name="lhh2", email="2432783449@qq.com")
users = [user1, user2]

# 第一种方法
schema = UserSchema(many=True)
res = schema.dump(users)
print(res)

# 第二种方法
schema = UserSchema()
res = schema.dump(users, many=True)
print(res)

